import { App, unref } from "vue";
import { I18nOptions, createI18n } from "vue-i18n";
import { useLocaleStoreWithout } from "@/store/modules/locale";
import { getLocale as getLocaleApi } from "@/api/modules/common";
import _ from "lodash-es";

export let i18n: ReturnType<typeof createI18n>;

/**
 * 创建i18n初始化配置
 * @returns i18nOptions
 */
async function createI18nOptions(): Promise<I18nOptions> {
  // 读取store
  const localeStore = useLocaleStoreWithout();
  // 当前语言
  const locale = localeStore.getLocale;
  // 加载当前语言对应包
  const message = await getlangRes(locale);
  return {
    legacy: false,
    locale,
    fallbackLocale: "en",
    messages: {
      [locale]: message,
    },
    globalInjection: true,
  };
}

async function getlangRes(lang: string) {
  const localeLang = await import(`./lang/${lang}/index.ts`);
  const apiLang = await getLocaleApi(lang);
  return _.merge(localeLang.default ?? {}, apiLang);
}

/**
 * 修改语言
 * @param lang 语言
 * @returns
 */
export async function changeLocale(lang: string) {
  // 获取当前语言
  const currentLocale = unref(i18n.global.locale);
  if (currentLocale === lang) {
    return;
  }
  // 判断当前是否已经加载
  if (!i18n.global.availableLocales.includes(lang)) {
    // 没有加载 重新加载
    i18n.global.setLocaleMessage(lang, await getlangRes(lang));
  }
  // 判断模式 修改语言
  if (i18n.mode === "legacy") {
    i18n.global.locale = lang;
  } else {
    (i18n.global.locale as any).value = lang;
  }
  // 修改网站标题
  document.querySelector("html")?.setAttribute("lang", lang);
}

/**
 * 注册i18n
 * @param app App
 */
export async function setupI18n(app: App) {
  const options = await createI18nOptions();
  i18n = createI18n(options);
  app.use(i18n);
}
